//
//  HMTabBar.swift
//  Weibo-walker
//
//  Created by 郭彬 on 16/3/2.
//  Copyright © 2016年 guobin. All rights reserved.
//

import UIKit

class HMTabBar: UITabBar {

    
    var  composeButtonClosure: (()->())?
    //    不用定义一个全局的 button 么？然后懒加载
    //    var button:(UIButton)
    
    //MARK:重写 init(frame：)方法
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //写setupUI
    private func setupUI() {
        addSubview(composeButton)
        backgroundImage = UIImage(named: "tabbar_background")
    }

    //MARK:懒加载
    lazy var composeButton:UIButton = {
        
        let button = UIButton()
        //添加点击方法
        
        button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        //设置 button 属性
        //设置按钮不同状态的图片与背景图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button"), forState: UIControlState.Normal)
        button.setBackgroundImage(UIImage(named: "tabbar_compose_button_highlighted"), forState: UIControlState.Highlighted)
        
        button.sizeToFit()
        return button
    }()
    
    // MARK: composeButtonClick
    //定义点击按钮的composeButtonClick方法
    func composeButtonClick (){
        
        print("加号的点击事件")
        composeButtonClosure?()
    }
    
    //布局子空间
   
    override func layoutSubviews() {
        
        super.layoutSubviews()
        //设置加号按钮位置
        //调整子控件的center,不能依靠于父控制的center,因为你不知道父控件是放在什么地方的
        composeButton.center = CGPoint(x: frame.width * 0.5, y: frame.height * 0.5)
        
        ///每一个按钮的宽度
        let childW = frame.size.width / 5
        //定义脚标记录当前button的位置
        var index = 0
        
        //遍历子控件调整'UITabBarButton'的宽度与位置
        for childView in subviews {
            
            //如果当前遍历的View是UITabBarButton
            if childView.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                //设置按钮的宽
                childView.frame.size.width = childW
                //设置按钮的x
                childView.frame.origin.x = CGFloat(index) * childW
                //index递增
                index++
                //如果当前遍历到'发现'，则把发现往后移动一个位置
                if index == 2 {
                    index++
                }
            }
        }
    }

}
